package com.kksoft.android.xiaoliaobaike;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.annotation.view.ViewInject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;

import com.kksoft.android.xiaoliaobaike.fetcher.FetchTaskService;
import com.kksoft.android.xiaoliaobaike.model.Series;

public class SeriesListActivity extends FinalActivity {

	public static final String TAG = "XiaoLiaoBeiKe";

	@ViewInject(id = R.id.seriesLv)
	ListView seriesLv;
	SimpleAdapter seriesAdapter;
	List<Map<String, Object>> seriesMapList;
	// @ViewInject(id = R.id.btnPageRange)
	// Button btnPageRange;
	// @ViewInject(id = R.id.btnFetchAll)
	// Button btnFetchAll;
	// @ViewInject(id = R.id.btnFetchPage)
	// Button btnFetchPage;
	// @ViewInject(id = R.id.scroll)
	// ScrollView scroll;
	// @ViewInject(id = R.id.txt)
	// TextView txt;

	FinalDb db;

	ProgressDialog progressDialog;

	FinalBitmap fb;
	int nextPage = 1;

	boolean running = false;

	int[] pageRange = { 0, 0 };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_series_list);

		fb = new FinalBitmap(this).init();// 必须调用init初始化FinalBitmap模块
		// fb.configBitmapMaxWidth(300);
		fb.configBitmapLoadThreadSize(5);
		fb.configDiskCacheSize(1024 * 1024 * 500);
		//fb.configDiskCachePath("/sdcard/XiaoLiaoBaiKe/");
		fb.configMemoryCacheSize(1024 * 1024 * 5);
		// fb.configLoadingImage(R.drawable.loading);

		progressDialog = new ProgressDialog(this);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage("正在解析数据...");
		progressDialog.setCancelable(false);

		db = FinalDb.create(SeriesListActivity.this, Const.DB_NAME, true);

		seriesMapList = new ArrayList<Map<String, Object>>();

		seriesAdapter = new SimpleAdapter(this, seriesMapList, R.layout.series_list_item, new String[] { "id", "title", "coverUrl", /*
																																 * "seriesId"
																																 * ,
																																 * "seriesUrl"
																																 * ,
																																 */
		"describe", "total", "firstUrl","seriesId" }, new int[] { R.id.id, R.id.title, R.id.coverUrl,
		/*
		 * R.id.seriesId, R.id.seriesUrl,
		 */R.id.describe, R.id.total, R.id.firstUrl,R.id.seriesId }) {

			// @Override
			// public View getView(int position, View convertView,
			// ViewGroup parent) {
			// // TODO Auto-generated method stub
			// View v = super.getView(position, convertView, parent);
			// ImageView iv = (ImageView)v.findViewById(R.id.coverUrl);
			//
			// //bitmap加载就这一行代码，display还有其他重载，详情查看源码
			// fb.display(iv,"http://img.baidu.com/img/image/ilogob.gif");
			// return v;
			// }
		};

		ViewBinder viewBinder = new ViewBinder() {

			public boolean setViewValue(View v, Object data, String text) {
				if (v instanceof ImageView) {
					ImageView iv = ((ImageView) v);
					if (data instanceof Integer) {
						iv.setImageResource((Integer) data);
					} else {
						try {
							iv.setImageResource(Integer.parseInt(text));
						} catch (NumberFormatException nfe) {
							// DisplayMetrics displayMetrics = MainActivity.this.getResources().getDisplayMetrics();
							// System.out.println("width:"+displayMetrics.widthPixels);
							fb.display(iv, text);
						}
					}
					return true;
				}
				return false;
			}
		};
		seriesAdapter.setViewBinder(viewBinder);

		seriesLv.setAdapter(seriesAdapter);

		seriesLv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				//TextView txtId = (TextView) view.findViewById(R.id.id);
				//Toast.makeText(SeriesListActivity.this, "当前选中的id为：" + txtId.getText(), Toast.LENGTH_SHORT).show();

				TextView seriesId = (TextView) view.findViewById(R.id.seriesId);

				Intent intent = new Intent(SeriesListActivity.this, ArticleListActivity.class);
				intent.putExtra("seriesId", Integer.valueOf(seriesId.getText().toString()));
				startActivity(intent);
			}
		});

		seriesLv.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				final TextView firstUrl = (TextView) view.findViewById(R.id.firstUrl);

				if (firstUrl.getText() == null || firstUrl.getText().length() == 0) {

				} else {
					AlertDialog.Builder builder = new AlertDialog.Builder(SeriesListActivity.this);
					builder.setMessage("打开链接？");
					builder.setNeutralButton("打开", new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(firstUrl.getText().toString()));

							// intent.setClassName("com.android.browser",
							// "com.android.browser.BrowserActivity");

							startActivity(intent);
						}
					});
					builder.setNegativeButton("放弃", new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});

					builder.create().show();
				}

				return true;
			}
		});

		refresh();
		
		IntentFilter filter = new IntentFilter() ;
		filter.addAction(Const.BROADCAST_MSG_FETCH_START);
		filter.addAction(Const.BROADCAST_MSG_FETCH_FINISH);
		
		receiver = new BroadcastReceiver(){
			@Override
			public void onReceive(Context context, Intent intent) {
				Toast.makeText(SeriesListActivity.this, intent.getAction(), Toast.LENGTH_SHORT).show();
				
				if(Const.BROADCAST_MSG_FETCH_START.equals(intent.getAction())) {
					Toast.makeText(SeriesListActivity.this, "开始抓取在线列表", Toast.LENGTH_LONG).show();
				} else if(Const.BROADCAST_MSG_FETCH_FINISH.equals(intent.getAction())) {
					long startTime = intent.getLongExtra(Const.FETCH_START_TIME, 0);
					long finishTime = intent.getLongExtra(Const.FETCH_FINISH_TIME, 0);
					
					AlertDialog.Builder builder = new AlertDialog.Builder(SeriesListActivity.this);
					builder.setMessage("抓取在线列表完成，用时："+(finishTime-startTime)+"s，是否刷新列表？");
					builder.setPositiveButton("我刷！", new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							SeriesListActivity.this.refresh();
						}
					});
					builder.setNegativeButton("不刷。", new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					
					builder.create().show();
				}
			}
		};
		// 注册广播接收器
		registerReceiver(receiver , filter);

	}
	
	BroadcastReceiver receiver;

	private void appendSeries(List<Series> seriesList, boolean clear) {
		if (clear) {
			seriesMapList.clear();
		}
		if (seriesList != null && seriesList.size() > 0) {
			for (Series s : seriesList) {
				seriesMapList.add(s.toMap());
				// render(s);
			}
		}
	}

	@Override
	protected void onDestroy() {
		progressDialog.dismiss();
		unregisterReceiver(receiver);
		
		super.onDestroy();
	}
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			
			builder.setTitle("笑料百科");
			builder.setMessage("确定退出吗？");
			
			builder.setCancelable(true);
			
			builder.setPositiveButton("退出", new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			builder.setNegativeButton("不，我继续看", null);
			
			builder.create().show();
		}
		return false;
	}

	private void refresh() {
		List<Series> seriesList = db.findAll(Series.class);
		appendSeries(seriesList, true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_refetch_series:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("建议在使用wifi的情况下获取所有漫画！");
			builder.setCancelable(false);
			builder.setNeutralButton("继续", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					startFetchAll();
				}
			});
			builder.setNegativeButton("放弃", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});

			builder.create().show();

			break;
		case R.id.menu_refresh:
			refresh();
			break;
		case R.id.menu_settings:
			Toast.makeText(this, "亲，这个功能还木有实现哦。。。", Toast.LENGTH_LONG).show();
			break;
		case R.id.menu_exit:
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void startFetchAll() {
		new Thread() {
			@Override
			public void run() {
				Intent service = new Intent(SeriesListActivity.this, FetchTaskService.class);
				service.putExtra("cmd", FetchTaskService.CMD_START_OR_RESTORE);
				
				startService(service);
			}
		}.start();
	}
	
	@Override
	public void finish() {
		Intent service = new Intent(SeriesListActivity.this, FetchTaskService.class);
		stopService(service);
		super.finish();
	}

}